<template>
  <div class="task-manage">
    <!-- 搜索栏 -->
    <el-form :model="searchParm" :inline="true" size="default">
      <el-form-item>
        <el-input placeholder="请输入课程名" v-model="searchParm.taskName" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" @click="searchBtn">查询</el-button>
        <el-button icon="Close" type="danger" plain @click="resetBtn"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table :data="tasks" style="width: 100%">
      <el-table-column
        prop="taskName"
        label="课程名"
        width="180"
        min-width="10%"
      ></el-table-column>
      <el-table-column
        prop="taskDescription"
        min-width="60%"
        label="课程介绍"
      ></el-table-column>
      <el-table-column
        prop="teacherName"
        min-width="20%"
        label="所属老师"
      ></el-table-column>
      <el-table-column
        prop="dueDate"
        label="截止日期"
        width="180"
        min-width="10%"
      >
        <template #default="{ row }">
          {{ row.dueDate ? row.dueDate.toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="editTask(scope.row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="deleteTask(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑课程" v-model="dialogVisible">
      <el-form :model="currentTask" :rules="rules" ref="taskForm">
        <el-form-item label="课程名" prop="taskName">
          <el-input v-model="currentTask.taskName"></el-input>
        </el-form-item>
        <el-form-item label="课程介绍" prop="taskDescription">
          <el-input
            v-model="currentTask.taskDescription"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker
            v-model="currentTask.dueDate"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateTask">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllTasks, deleteTaskById, updateTaskById } from '@/api/task.js'
import useUserInfoStore from '@/stores/userInfo.js'
useUserInfoStore()

const searchParm = reactive({
  taskName: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const tasks = ref([])

const currentTask = reactive({
  id: null,
  taskName: '',
  taskDescription: '',
  dueDate: '',
  createDat: null,
  updateDat: null,
  teacherId: null,
  teacherName: null
})

const dialogVisible = ref(false)
const taskForm = ref(null)

// 表单验证规则
const rules = reactive({
  taskName: [
    { required: true, message: '请输入课程名', trigger: 'blur' },
    { min: 3, max: 20, message: '课程名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  taskDescription: [
    { required: true, message: '请输入课程介绍', trigger: 'blur' },
    { max: 1000, message: '课程介绍不能超过1000个字符', trigger: 'blur' }
  ],
  dueDate: [
    { required: true, message: '请选择截止日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        const today = new Date()
        today.setHours(0, 0, 0, 0)
        if (value) {
          const date = new Date(value)
          if (date < today) {
            callback(new Error('截止日期不能小于当天'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

// 获取任务列表
const fetchTasks = async () => {
  try {
    const response = await getAllTasks(searchParm)
    tasks.value = response.data.map(task => {
      console.log(tasks)
      return {
        ...task,
        dueDate: task.dueDate ? formatDate(parseDate(task.dueDate)) : '' // 格式化日期为字符串
      }
    })
  } catch {
    ElMessage.error('获取课程列表失败')
  }
}

// 更新任务的函数
const updateTask = async () => {
  try {
    await taskForm.value.validate()
    let taskToSend = {
      ...currentTask,
      dueDate: currentTask.dueDate
        ? convertLocalToUTC(new Date(currentTask.dueDate)).toISOString()
        : null,
      updateDat: new Date().toISOString() // 更新时间设置为当前UTC时间
    }

    if (currentTask.id !== null) {
      await updateTaskById(currentTask.id, taskToSend)
      await fetchTasks() // 重新获取任务列表
      dialogVisible.value = false // 关闭对话框
      ElMessage.success('编辑课程成功')
    } else {
      ElMessage.error('无效的课程ID')
    }
  } catch (error) {
    console.error('编辑课程失败:', error)
    ElMessage.error('格式不符合规范')
  }
}

// 打开编辑任务对话框的函数

const editTask = task => {
  currentTask.id = task.taskId // 确保这里使用的是 taskid 而不是 id
  currentTask.taskName = task.taskName
  currentTask.taskDescription = task.taskDescription
  currentTask.dueDate = task.dueDate // 直接使用从数据库中获取的本地时间字符串
  currentTask.teacherId = task.teacherId
  currentTask.teacherName = task.teacherName
  dialogVisible.value = true
}

// 删除任务的函数
const deleteTask = async id => {
  try {
    if (id === null || id === undefined) {
      ElMessage.error('无效的课程ID')
      return
    }
    const confirmed = await ElMessageBox.confirm(
      '你确定要删除这个课程吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    if (confirmed) {
      await deleteTaskById(id)
      await fetchTasks()
      ElMessage.success('删除课程成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除课程失败')
    } else {
      ElMessage.info('已取消删除')
    }
  }
}

// 查询按钮点击事件
const searchBtn = async () => {
  try {
    const response = await getAllTasks(searchParm)
    tasks.value = response.data.map(task => {
      return {
        ...task,
        dueDate: parseDate(task.dueDate)
      }
    })
  } catch {
    ElMessage.error('查询课程失败')
  }
}

// 重置按钮点击事件
const resetBtn = () => {
  searchParm.taskName = ''
  fetchTasks() // 重新获取任务列表
}

// 解析日期数组为Date对象
const parseDate = dateArray => {
  if (!dateArray || !Array.isArray(dateArray)) {
    return null
  }
  // 确保数组长度足够
  if (dateArray.length < 5) {
    return null
  }
  // 解析日期数组
  return new Date(
    dateArray[0],
    dateArray[1] - 1,
    dateArray[2],
    dateArray[3],
    dateArray[4],
    dateArray[5] || 0
  )
}

// 格式化日期为指定格式（本地时间）
const formatDate = date => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 本地时间（CST）转换为UTC时间
const convertLocalToUTC = localDate => {
  const offset = 8 * 60 * 60 * 1000 // CST时区偏移量
  return new Date(localDate.getTime() + offset)
}

fetchTasks()
</script>

<style scoped>
.task-manage {
  margin: 20px;
  display: flex;
  flex-direction: column;
}
</style>
